package rocketmq.demo.async.trans;

import rocketmq.demo.utils.MqConfig;

import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendCallback;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.remoting.common.RemotingHelper;

/**
 * <pre>
 * Reliable asynchronous transmission  异步传输
 * 
 * Application: asynchronous transmission is
 * generally used in response time sensitive business scenarios.
 * </pre>
 */
public class AsyncProducer {
	public static void main(String[] args) throws Exception {
		// Instantiate with a producer group name.
		DefaultMQProducer producer = new DefaultMQProducer(MqConfig.GROUP_TEST);

		// 指定nameServer的地址
		producer.setNamesrvAddr(MqConfig.DEFAULT_NAME_SRV_ADDR);

		// Launch the instance.
		producer.start();
		producer.setRetryTimesWhenSendAsyncFailed(0);
		for (int i = 0; i < 5; i++) {
			final int index = i;
			// Create a message instance, specifying topic, tag and message
			// body.
			Message msg = new Message(MqConfig.TOPIC_ASYNC, MqConfig.TAG_TEST,
					"OrderID188",
					("Hello Async Message world" + i)
							.getBytes(RemotingHelper.DEFAULT_CHARSET));
			producer.send(msg, new SendCallback() {
				@Override
				public void onSuccess(SendResult sendResult) {
					System.out.printf("%-10d OK %s %n", index, sendResult);
				}

				@Override
				public void onException(Throwable e) {
					System.out.printf("%-10d Exception %s %n", index, e);
					e.printStackTrace();
				}
			});
		}
		// Shut down once the producer instance is not longer in use.
		producer.shutdown();
	}
}